package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping("/account")
@SessionAttributes({"account","myList","authenticated"})
public class AccountController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private CatalogService catalogService;

    @Autowired
    private CartService cartService;

    @Autowired
    private Cart cart;

    private Account account = new Account();
    private List<Product> myList;
    private boolean authenticated;

    private static final List<String> LANGUAGE_LIST;
    private static final List<String> CATEGORY_LIST;

    static {
        List<String> langList = new ArrayList<String>();
        langList.add("ENGLISH");
        langList.add("CHINESE");
        LANGUAGE_LIST = Collections.unmodifiableList(langList);

        List<String> catList = new ArrayList<String>();
        catList.add("FISH");
        catList.add("DOGS");
        catList.add("REPTILES");
        catList.add("CATS");
        catList.add("BIRDS");
        CATEGORY_LIST = Collections.unmodifiableList(catList);
    }

    @GetMapping("/signonForm")
    public  String signonForm(Model model) {
        return "account/SignonForm";
    }

    @PostMapping("/signon")
    public String signon(HttpSession session, String username, String password, Model model) {

        password = MD5Util.string2MD5(password);
        Account account = accountService.getAccount(username, password);
        if (account == null) {
            model.addAttribute("msg", "Invalid username or password.  Signon failed.");
            clear();
            return "account/SignonForm";
        } else {
            List<CartItem> cartItemList = cartService.getCartItemListByUserid(account.getUsername());
            Iterator<CartItem> iterator = cartItemList.iterator();
            while (iterator.hasNext()) {
                int i = 0;
                CartItem cartItem = iterator.next();
                Item item = catalogService.getItem(cartItem.getItemId());
                while (i < cartItem.getQuantity()) {
                    cart.addItem(item, true);
                    i++;
                }
            }
            session.setAttribute("cart", cart);

            account.setPassword(null);
            myList = catalogService.getProductListByCategory(account.getFavouriteCategoryId());
            authenticated = true;
            model.addAttribute("account", account);
            model.addAttribute("myList", myList);
            model.addAttribute("authenticated", authenticated);
            return "catalog/Main";
        }
    }

    @GetMapping("/signoff")
    public String signoff(Model model) {
        clear();
        model.addAttribute("account",null);
        model.addAttribute("cart", null);
        model.addAttribute("authenticated", false);
//        List<Category> categoryList = catalogService.getCategoryList();
//        model.addAttribute("account", null);
        return "catalog/Main";
    }

    @GetMapping("/newAccountForm")
    public String newAccountForm(Model model) {
        model.addAttribute("account", new Account());
        model.addAttribute("LANGUAGE_LIST", LANGUAGE_LIST);
        model.addAttribute("CATEGORY_LIST", CATEGORY_LIST);
        return "account/NewAccountForm";
    }

    @PostMapping("/newAccount")
    public String newAccount(@ModelAttribute(value = "newAccount") Account account, HttpSession session, String repeatedPassword, Model model) {
        if (account.getUsername() == null || account.getPassword() == null || account.getPassword().length() == 0 || repeatedPassword == null || repeatedPassword.length() == 0) {
            String msg = "用户名或密码不能为空";
            session.setAttribute("msg", msg);
            return "redirect:/account/newAccountForm";
        } else if (!account.getPassword().equals(repeatedPassword)) {
            String msg = "两次密码不一致";
            session.setAttribute("msg", msg);
            return "redirect:/account/newAccountForm";
        } else {
            //MD5加密
            String pwd = MD5Util.string2MD5(account.getPassword());
            account.setPassword(pwd);

            accountService.insertAccount(account);
            account = accountService.getAccount(account.getUsername());
            myList = catalogService.getProductListByCategory(account.getFavouriteCategoryId());
            authenticated = true;
            model.addAttribute("account", account);
            model.addAttribute("myList", myList);
            model.addAttribute("authenticated", authenticated);
            return "redirect:/catalog/viewMain";
        }
    }

    @GetMapping("/editAccountForm")
    public String editAccountForm(@SessionAttribute("account") Account account, Model model) {
        if (account != null) {
            model.addAttribute("account", account);
            model.addAttribute("LANGUAGE_LIST", LANGUAGE_LIST);
            model.addAttribute("CATEGORY_LIST", CATEGORY_LIST);
            return "account/EditAccountForm";

        }
        return "account/SignonForm";
    }

    @PostMapping("/editAccount")
    public String editAccount(Account account, String repeatedPassword, Model model) {
        if (account.getPassword() == null || account.getPassword().length() == 0 || repeatedPassword == null || repeatedPassword.length() == 0) {
            String msg = "密码不能为空";
            model.addAttribute("msg", msg);
            return "account/EditAccountForm";
        } else if (!account.getPassword().equals(repeatedPassword)) {
            String msg = "两次密码不一致";
            model.addAttribute("msg", msg);
            return "account/EditAccountForm";
        } else {
            //MD5加密
            String pwd = MD5Util.string2MD5(account.getPassword());
            account.setPassword(pwd);
            accountService.updateAccount(account);
            account = accountService.getAccount(account.getUsername());
            myList = catalogService.getProductListByCategory(account.getFavouriteCategoryId());
            authenticated = true;
            model.addAttribute("account", account);
            model.addAttribute("moList", myList);
            model.addAttribute("authenticated", authenticated);

            return "redirect:/catalog/viewMain";
        }
    }

    public boolean isAuthenticated() {
        return authenticated && account != null && account.getUsername() != null;
    }

    public void clear() {
        account = new Account();
        myList = null;
        authenticated = false;
    }
}
